<template>
  <view style="text-align: center; display: inline-block; flex-wrap: wrap">
    <!-- <view class="machine-list-card" :key="item.id" v-for="item in cartlist">
      <view style="display: flex">
        <view class="left">
          <view class="img"><img :src="item.img" class="img" /></view>
        </view>
        <view class="right">
          <view class="info-item">
            <view class="info-item-title">{{ item.title }}</view>
          </view>
          <view class="info-item">
            <view class="info-item-title">{{ item.describe }}</view>
          </view>
          <view class="info-item">
            <view class="info-item-title">¥{{ item.price }}</view>
          </view>
          <view class="info-item">
            <view class="info-item-title">
              数量
              <input
                type="number"
                min="1"
                max="99"
                name="num"
                v-model="item.num"
                class="form-control"
                placeholder="请输入 "
              />
            </view>
          </view>
        </view>
      </view>
    </view> -->
    <el-table
      :data="cartlist"
      stripe
      style="width: 100%"
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column label="图片" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <view class="img"><img :src="scope.row.img" class="img" /></view>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="商品名" width="180" />
      <el-table-column prop="describe" label="商品描述" width="180" />
      <el-table-column prop="price" label="商品价格" width="180" />
      <el-table-column label="商品数量" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <input
              type="number"
              min="1"
              max="99"
              name="num"
              v-model="scope.row.num"
              class="form-control"
              placeholder="请输入 "
            />
          </div>
        </template>
      </el-table-column>
    </el-table>
  </view>

  <div style="margin: 15px 0">
    统计结果， {{ sumPrice }},结算 ：{{ sumNum }}
  </div>
  <el-button type="primary" @click="toggleSelection()"
    >Clear selection</el-button
  >
  <el-button type="danger" @click="removecard()">删除选中的购物车</el-button>
  <el-button type="success" @click="checkin()">结算</el-button>
  <el-button @click="closed()">返回</el-button>
</template>

<script setup>
import { getcart, commitcart, removecartbyids } from "../utils/cart";
import { computed, inject, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
const store = useStore();
const router = useRouter();
const cartlist = ref([]);
const multipleTableRef = ref();
const multipleSelection = ref([]);

const selectable = (row) => ![].includes(row.id);
const toggleSelection = (rows, ignoreSelectable) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(
        row,
        undefined,
        ignoreSelectable
      );
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
};
function removecard() {
  if (multipleSelection.value.length == 0) {
    ElMessage({
      message: "请先选择要删除的商品",
      type: "warning",
    });
    return;
  } else {
    let ids = "";
    ElMessageBox.confirm("是否确认删除选定的购物车商品？", "是否确认？", {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      type: "warning",
      center: true,
    })
      .then(() => {
        for (let i = 0; i < multipleSelection.value.length; i++) {
          if (i + 1 == multipleTableRef.value.length)
            ids += multipleSelection.value[i].id;
          ids += multipleSelection.value[i].id + ",";
        }
        console.log("ids", ids);
        removecartbyids(ids).then((response) => {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          mygetdata();
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "Delete canceled",
        });
      });
  }
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("val", val);
};
const sumNum = computed(() => {
  let sum1 = 0;
  for (let i = 0; i < cartlist.value.length; i++) {
    sum1 += cartlist.value[i].num * 1;
  }
  return "总数量 ：" + sum1 + "   ";
});
const sumPrice = computed(() => {
  let sum = 0;
  for (let i = 0; i < cartlist.value.length; i++) {
    sum += cartlist.value[i].num * cartlist.value[i].price;
  }
  console.log("sumprice:", sum);
  return "总金额 ：" + sum + "   ";
});
const checkedGoods = ref([]);
function closed() {
  router.back();
}
function checkin() {
  if (multipleSelection.value.length == 0) {
    ElMessageBox.confirm("是否要提交购物车所有商品?", "Warning", {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      type: "warning",
      center: true,
    })
      .then(() => {
        for (let i = 0; i < cartlist.value.length; i++) {
          let goodobj = {
            id: cartlist.value[i].id,
            updateBy: store.getters.getUser.username,
            status: "已提交",
          };
          commitcart(goodobj).then((response) => {
            mygetdata(); //重新读取购物车中的数据
            // router.go(0); // 刷新页面
          });
        }
        alert("结算完成");
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "结算取消",
        });
      });
  } else {
    for (let i = 0; i < multipleSelection.value.length; i++) {
      let goodobj = {
        id: multipleSelection.value[i].id,
        updateBy: store.getters.getUser.username,
        status: "已提交",
      };
      commitcart(goodobj).then((response) => {
        mygetdata(); //重新读取购物车中的数据
        // router.go(0); // 刷新页面
      });
    }
    alert("结算完成");
  }
}
function mygetdata() {
  //读取购物车中的所有商品
  getcart({ status: "未提交", createBy: store.getters.getUser.username }).then(
    (response) => {
      if (response.code == 401) {
        //认证失败，无法访问系统资源,跳转到登录页面
        router.push({ path: "/login" });
        return;
      }
      cartlist.value.splice(0, cartlist.value.length);
      for (let index in response.rows) {
        let newgood = {
          id: response.rows[index],
          img: "/a1.jpg",
          title: "测试",
          describe: "新产品",
          price: 121,
          num: 3,
          memo: "无",
        };
        response.rows[index].img = response.rows[index].img;
        newgood.id = response.rows[index].id;
        newgood.img = response.rows[index].img;
        newgood.title = response.rows[index].title;
        newgood.describe = response.rows[index].mydescribe;
        newgood.price = response.rows[index].price;
        newgood.num = response.rows[index].num;
        newgood.memo = response.rows[index].memo;
        cartlist.value.push(newgood);
      }
    }
  );
}
onMounted(() => {
  mygetdata();
});
</script>

<style scoped>
.machine-list-card {
  /* width: 850px; */
  height: 100px;
  /* margin: 5px auto; */
  display: flex;
  flex-direction: row;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 5px 5px 10px rgba(160, 160, 160, 0.3);
  margin-bottom: 10px;
  /* margin-right: 10px; */
}

.check1 {
  width: 80px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.left {
  width: 80px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.right {
  min-width: 600px;
  height: 100px;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  /* flex-direction: column; */
  justify-content: space-around;
}

.img {
  width: 80px;
  height: 80px;
}

.img image {
  width: 80px;
  height: 80px;
}

.info-item {
  display: flex;
  white-space: nowrap;
  display: inline-grid;
  align-content: center;
}

.info-item-title {
  /* font-weight: bold; */
  font-size: 20px;
  width: 4em;
  text-align: justify;
  text-align-last: justify;
}

.info-item-content {
  margin-left: 10px;
  overflow: hidden;
}
</style>
